import koa from 'koa';
import logger from 'koa-logger';
import session from 'koa-generic-session';
import redisStore from 'koa-redis';
import config from 'config';
import router from './router';
import cors from 'koa-cors';
import http from 'http';
import _socketio from 'socket.io';
import _debug from 'debug';

const debug = _debug('app:');

const app = koa();

/**
* Catch & Handle errors
*/
app.use(function* (next) {
  try {
    yield next;
  } catch (e) {
    console.error(e.stack);

    this.status = e.status || 500;
    this.body = {
      status: e.code,
      message: e.message
    }
  }
});

app.keys = ['wx-sso', 'sso-wx'];
app.use(session({
  key: 'wx-sso',
  prefix: 'wx-sso:',
  store: new redisStore(config.redis),
  cookie: {
    path: '/',
    httpOnly: true,
    maxage: null,
    rewrite: true,
    signed: true,
    domain: config.session_domain
  }
}));

app.use(logger());
app.use(cors());

app.use(router().routes());
const server = http.createServer(app.callback());
const io = _socketio(server);

io.on('connection', function(socket){
  debug(`a client connected`);
});

app.context.io = io;

export default server;
